import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;
import java.io.*;
import java.sql.*;

public class BlobUpload
{
	public static void main(String[] args)
	{
		try
		{
			DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
			Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@146.187.134.17:1542:oracle10g", "cscd494",	"R3tral435");
			
			//conn.setAutoCommit(false);
			BlobUpload bu = new BlobUpload();
			bu.uploadToDB(conn, "PracticeInGen.java");
			//bu.downloadBlob(conn);
		}
		catch(SQLException sqlError)
		{
			sqlError.printStackTrace();
		}

	}

	public void uploadToDB(Connection conn, String filename)
	{
		try
		{
			//conn.setAutoCommit(false);
			PreparedStatement  uploadStmt = conn.prepareStatement("select document_s1.nextval from dual");
			ResultSet rset = uploadStmt.executeQuery();
			rset.next();
			int index = rset.getInt(1);
			System.out.println(index);
			uploadStmt = conn.prepareStatement("INSERT INTO DOCUMENTS (document_id, document_name, document_file) VALUES(?,'test.java',?)");
			
			FileInputStream is = null;
			File dir = new File(filename);
			
			if(dir.isDirectory())
			{
				String[] dirList = dir.list();
				for(int i=0; i<dirList.length;i++)
				{
					File file = new File(filename,dirList[i]);
					is = new FileInputStream(file);
					uploadStmt.setInt(1, index);
					uploadStmt.setBinaryStream(2, is, (int)file.length());
					uploadStmt.executeUpdate();
				}
			}
			else
			{
				File file = new File(filename);
				is = new FileInputStream(file);
				uploadStmt.setInt(1, index);
				uploadStmt.setBinaryStream(2, is, (int)file.length());
				uploadStmt.execute();
			}
			is.close();
			uploadStmt.close();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		
	}
	
	public void downloadBlob(Connection conn)
	{
		try
		{
			PreparedStatement downloadBlob = conn.prepareStatement("SELECT document_name FROM DOCUMENTS WHERE document_id = 43");
			ResultSet test = downloadBlob.executeQuery();
			test.next();
			System.out.println(test.getString("document_name"));
		}
		catch(SQLException sqlError)
		{
			sqlError.printStackTrace();
		}
	
	}
	
	public void insertQuestion(Connection conn)
	{
		//Question_Content
		//Question -> question_content_id
		//Source_File -> question_id
		//
		
		
	}
}
